package activity.addCamera;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;
import com.hichip.sdk.HiChipP2P;

import activity.setting.WifiSetToDeviceActivity;
import base.HiActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import custom.dialog.NiftyDialogBuilder;
import main.MainActivity;
import utils.EmojiFilter;
import utils.FullCharFilter;
import utils.HiToast;
import utils.HiTools;
import utils.SpcialCharFilterWIFISET;
import utils.WifiAdmin;

/**
 * 支持WiFi设置 就配置WIFI
 */
public class ConfigWiFiToDeviceTwoActivity extends HiActivity implements View.OnClickListener, ICameraIOSessionCallback {
    private String mUid;
    @BindView(R.id.title) TitleView title;
    @BindView(R.id.et_wifi_name) EditText et_wifi_name;
    @BindView(R.id.et_wifi_password) EditText et_wifi_password;
    @BindView(R.id.iv_to_choice) ImageView iv_to_choice;
    @BindView(R.id.tv_hint) TextView tv_hint;
    @BindView(R.id.tv_skip_set_wifi) TextView tv_skip_set_wifi;
    @BindView(R.id.but_setting) TextView but_setting;

    @BindView(R.id.tv_current_uid) TextView tv_current_uid;

    private MyCamera mMyCamera;
    private String camera_nick;
    private String camera_username;
    private String camera_password;
    private String mWiFiName;
    private String mWiFiPassWord;
    private String mCurrentPhoneWiFi;//上面界面传过来的WIFI
    private boolean isAP;
    private WifiManager wifiManager;
    private String mDeviceWiFi;//当前手机连接的WIFI

    private int mLoginNum = 0;//统计当前登录次数
    private PopupWindow popupWindow;
    private boolean isSupportFullChar=false;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_configwifi_todevice_two;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initViewAndData();
        setListeners();
    }

    private void setListeners() {
        iv_to_choice.setOnClickListener(this);
        tv_hint.setOnClickListener(this);
        tv_skip_set_wifi.setOnClickListener(this);
        but_setting.setOnClickListener(this);
    }

    private void getIntentData() {
        mUid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        isAP = getIntent().getBooleanExtra("isAP", false);
        camera_nick = getIntent().getStringExtra("nick");
        camera_username = getIntent().getStringExtra("username");
        camera_password = getIntent().getStringExtra("password");
        mCurrentPhoneWiFi = getIntent().getStringExtra("mCurrentPhoneWiFi");
        isSupportFullChar=getIntent().getBooleanExtra("isSupportFullChar",false);
        mMyCamera = new MyCamera(getApplicationContext(), camera_nick, mUid, camera_username, camera_password);
    }

    private void initViewAndData() {
        title.setTitle(getString(R.string.title_wireless_config));
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setRightTxtBack(R.mipmap.x_bule);
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        ConfigWiFiToDeviceTwoActivity.this.finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_IV_RIGHT:
                        Intent intent=new Intent(ConfigWiFiToDeviceTwoActivity.this,MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent,true);
                        break;
                }
            }
        });
        tv_hint.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tv_hint.getPaint().setAntiAlias(true);

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo != null && !TextUtils.isEmpty(wifiInfo.getSSID())) {
            String ssid = wifiInfo.getSSID().substring(1, wifiInfo.getSSID().length() - 1);
            if (!ssid.startsWith(HiDataValue.START_WITH_IPCAM)) {
                et_wifi_name.setText(ssid);
                et_wifi_name.setSelection(ssid.length());
            }
        }

        if (!TextUtils.isEmpty(mCurrentPhoneWiFi) && !mCurrentPhoneWiFi.startsWith(HiDataValue.START_WITH_IPCAM)) {
            et_wifi_name.setText(mCurrentPhoneWiFi);
            et_wifi_name.setSelection(mCurrentPhoneWiFi.length());
        }
        tv_current_uid.setText(mUid);


        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        String SSID = wifiManager.getConnectionInfo().getSSID();
        mDeviceWiFi = SSID.substring(1, SSID.length() - 1);
        if (isSupportFullChar) {
            et_wifi_password.setFilters(new InputFilter[] { new InputFilter.LengthFilter(63), new FullCharFilter(this), new EmojiFilter() });
        } else {
            et_wifi_password.setFilters(new InputFilter[] { new InputFilter.LengthFilter(31), new SpcialCharFilterWIFISET(this),new EmojiFilter() });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_to_choice:
                LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
                boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if(ok){
                    Intent intent = new Intent(ConfigWiFiToDeviceTwoActivity.this, PhoneWiFiListActivity.class);
                    startActivityForResult(intent, 110);
                }else {
                    AlertDialog.Builder dialog=new AlertDialog.Builder(this);
                    dialog.setTitle(getString(R.string.tip_reminder)).setMessage(getString(R.string.open_location));
                    dialog.setPositiveButton(getString(R.string.go_to_open), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 1315);
                        }
                    });
                    dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    dialog.show();
                }
                break;
            case R.id.tv_hint://提示
                View customView = View.inflate(ConfigWiFiToDeviceTwoActivity.this, R.layout.pup_wifi_require, null);
                PopupWindow popupWindow = new PopupWindow(customView);
                ColorDrawable cd = new ColorDrawable(-000);
                popupWindow.setBackgroundDrawable(cd);
                popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setFocusable(true);
                popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
                TextView tv_know = customView.findViewById(R.id.tv_know);
                tv_know.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
                break;
            case R.id.tv_skip_set_wifi:
                handSkip();
                break;
            case R.id.but_setting://   去配置
                mWiFiName = et_wifi_name.getText().toString();
                mWiFiPassWord = et_wifi_password.getText().toString().trim();
                if (TextUtils.isEmpty(mWiFiName) || TextUtils.isEmpty(mWiFiPassWord)) {
                    HiToast.showToast(this, getString(R.string.wifi_name_pd_not_empty));
                    return;
                }
                if(isSupportFullChar){
                    if (HiTools.isMaxLength(mWiFiName, 32)) {
                        HiToast.showToast(this, getString(R.string.toast_ssid_tolong));
                        return;
                    }
                    boolean isMax = HiTools.isMaxLength(mWiFiPassWord, 63);
                    if (isMax) {
                        HiToast.showToast(this, getString(R.string.tips_input_tolong));
                        return;
                    }
                }else {
                    if (mWiFiPassWord.getBytes().length > 31) {
                        HiToast.showToast(this, getString(R.string.tips_input_tolong));
                        return;
                    }
                    if (mWiFiName.getBytes().length > 31) {
                        HiToast.showToast(this, getString(R.string.toast_ssid_tolong));
                        return;
                    }
                }
                if (mWiFiPassWord.length() < 8) {
                    HiToast.showToast(this, getString(R.string.wifi_pd_least_8));
                    return;
                }
                showLoadDialog(getString(R.string.configing), false, false);
                HiToast.showToast(this, getString(R.string.wait_30));
                if (mMyCamera != null && mMyCamera.getConnectState() == HiCamera.CAMERA_CONNECTION_STATE_LOGIN) {
                    mMyCamera.disconnect();
                }
                mMyCamera.registerIOSessionListener(this);
                mMyCamera.connect();
                if (isAP) {
                    mLoginNum = 0;
                    handIsAP();
                } else {
                    if (mMyHandler != null) {
                        mMyHandler.removeCallbacksAndMessages(null);
                    }
                    handNotIsAP();
                }
                break;
        }
    }

    private Handler mMyHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };


    private void handNotIsAP() {
        mMyHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mLoadDialoging != null && mLoadDialoging.isShowing() && !ConfigWiFiToDeviceTwoActivity.this.isFinishing()) {
                    dissmissLoadDialog();
                    View customView = View.inflate(ConfigWiFiToDeviceTwoActivity.this, R.layout.pup_why_config_fail_disconnect, null);
                    popupWindow = new PopupWindow(customView);
                    ColorDrawable cd = new ColorDrawable(-000);
                    popupWindow.setBackgroundDrawable(cd);
                    popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                    popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                    popupWindow.setFocusable(true);
                    if (!popupWindow.isShowing()) {
                        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
                    }
                    TextView tv_know = customView.findViewById(R.id.tv_know);
                    tv_know.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupWindow.dismiss();
                        }
                    });
                }
            }
        }, 30000);
    }

    private CountDownTimer timer;

    private void handIsAP() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new CountDownTimer(40000, 1500) {//40秒才够配置失败,设备退回AP热点模式
            @Override
            public void onTick(long millisUntilFinished) {
                if (mMyCamera != null) {
                    mMyCamera.connect();
                }
            }

            @Override
            public void onFinish() {
                HiToast.showToast(ConfigWiFiToDeviceTwoActivity.this, getString(R.string.config_fail));
                dissmissLoadDialog();
                if (popupWindow == null) {
                    View customView = View.inflate(ConfigWiFiToDeviceTwoActivity.this, R.layout.pup_ap_config_fail, null);
                    popupWindow = new PopupWindow(customView);
                    ColorDrawable cd = new ColorDrawable(-000);
                    popupWindow.setBackgroundDrawable(cd);
                    popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                    popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                    popupWindow.setFocusable(true);
                    if (!popupWindow.isShowing()) {
                        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
                    }
                    TextView tv_know = customView.findViewById(R.id.tv_know);
                    tv_know.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mMyCamera != null) {
                                mMyCamera.unregisterIOSessionListener(ConfigWiFiToDeviceTwoActivity.this);
                            }
                            pupDismiss();
                        }
                    });
                }
                return;
            }
        };
        timer.start();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mMyCamera != null) {
            mMyCamera.unregisterIOSessionListener(this);
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (isAP) {
            mLoginNum = 0;
        }
        if (mMyHandler != null) {
            mMyHandler.removeCallbacksAndMessages(null);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 110 && resultCode == RESULT_OK) {
            String ssid = data.getStringExtra("configssid");
            if (!TextUtils.isEmpty(ssid)) {
                et_wifi_name.setText(ssid);
            }
        }
        if(requestCode == 110 && resultCode == RESULT_OK){
            LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
            boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
            if(ok){
                Intent intent = new Intent(ConfigWiFiToDeviceTwoActivity.this, PhoneWiFiListActivity.class);
                startActivityForResult(intent, 110);
            }
        }
    }

    private void handSkip() {
        NiftyDialogBuilder dialog = NiftyDialogBuilder.getInstance(this);
        dialog.withMessageLayoutHWrapW(HiTools.dip2px(this, 270));
        if (isAP) {
            dialog.withTitle(getString(R.string.tip_reminder)).withMessage(getString(R.string.device_spot_ssid)+ mDeviceWiFi + "\n\n" + getString(R.string.each_connect_spot));
        } else {
            dialog.withTitle(getString(R.string.tip_reminder)).withMessage(getString(R.string.ensure_wired_connect));
        }
        dialog.withButton1Text(getString(R.string.cancel)).withButton2Text(getString(R.string.confirm_skip));
        dialog.setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //确认跳过
        dialog.setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                DoneGoToMain();
            }
        });
        dialog.show();
    }

    private void DoneGoToMain() {
       for (MyCamera camera: HiDataValue.CameraList){
           if(camera.getUid().equals(mMyCamera.getUid())){
               Intent broadcast = new Intent();
               broadcast.putExtra("mIsAdd", true);
               broadcast.setAction(HiDataValue.ACTION_CAMERA_INIT_END);
               sendBroadcast(broadcast);
               Intent intent=new Intent(ConfigWiFiToDeviceTwoActivity.this,MainActivity.class);
               startActivity(intent);
               HiToast.showToast(ConfigWiFiToDeviceTwoActivity.this, getString(R.string.config_net_success));
               return;
           }
       }
        HiToast.showToast(ConfigWiFiToDeviceTwoActivity.this, getString(R.string.add_success));
        mMyCamera.saveInDatabase(ConfigWiFiToDeviceTwoActivity.this);
        mMyCamera.saveInCameraList();
        Intent intentBroadcast = new Intent();
        intentBroadcast.setAction(HiDataValue.ACTION_CAMERA_INIT_END);
        sendBroadcast(intentBroadcast);
        Intent intent=new Intent(ConfigWiFiToDeviceTwoActivity.this,TakeNameToCamActivity.class);
        intent.putExtra(HiDataValue.EXTRAS_KEY_UID,mMyCamera.getUid());
        startActivity(intent);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_SESSION_STATE:
                    handSessionState(msg);
                    break;
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {//成功
                        switch (msg.arg1) {
                            case HiChipDefines.HI_P2P_SET_WIFI_PARAM:
                                break;
                            case HiChipDefines.HI_P2P_SET_WIFI_CHECK:
                                dissmissLoadDialog();
                                byte wifiSelectMode = (byte) 0;
                                byte wifiSelectEncType = (byte) 3;
                                // 这个命令是直接设置   不管密码是否正确
                                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_WIFI_PARAM, HiChipDefines.HI_P2P_S_WIFI_PARAM.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, 0, wifiSelectMode, wifiSelectEncType, mWiFiName.getBytes(), mWiFiPassWord.getBytes()));
                                DoneGoToMain();
                                break;
                        }
                    } else {
                        switch (msg.arg1) {
                            case HiChipDefines.HI_P2P_SET_WIFI_PARAM:
                                HiToast.showToast(ConfigWiFiToDeviceTwoActivity.this, getString(R.string.tips_wifi_setting_fail));
                                dissmissLoadDialog();
                                break;
                            case HiChipDefines.HI_P2P_SET_WIFI_CHECK:
                                dissmissLoadDialog();
                                if (mLoadDialoging != null && !mLoadDialoging.isShowing()) {
                                    return;
                                }
                                View customView = View.inflate(ConfigWiFiToDeviceTwoActivity.this, R.layout.pup_why_config_fail, null);
                                PopupWindow popupWindow = new PopupWindow(customView);
                                ColorDrawable cd = new ColorDrawable(-000);
                                popupWindow.setBackgroundDrawable(cd);
                                popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                                popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                                popupWindow.setFocusable(true);
                                popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
                                TextView tv_know = customView.findViewById(R.id.tv_know);
                                tv_know.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        popupWindow.dismiss();
                                    }
                                });
                                break;
                        }
                    }
                    break;
            }
        }
    };

    private void handSessionState(Message msg) {
        switch (msg.arg1) {
            case HiCamera.CAMERA_CONNECTION_STATE_LOGIN:
                byte wifiSelectMode = (byte) 0;
                byte wifiSelectEncType = (byte) 3;
                if (isAP) {
                    mLoginNum++;
                    if (mLoginNum == 2) {//第二次收到Login
                        dissmissLoadDialog();
                        if (HiTools.isWifiConnected(ConfigWiFiToDeviceTwoActivity.this)) {
                            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                            String SSID = wifiManager.getConnectionInfo().getSSID();
                            SSID = SSID.substring(1, SSID.length() - 1);
                            if (!TextUtils.isEmpty(SSID) && SSID.equals(mDeviceWiFi)) {
                                if (popupWindow == null) {
                                    View customView = View.inflate(ConfigWiFiToDeviceTwoActivity.this, R.layout.pup_ap_config_fail, null);
                                    popupWindow = new PopupWindow(customView);
                                    ColorDrawable cd = new ColorDrawable(-000);
                                    popupWindow.setBackgroundDrawable(cd);
                                    popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                                    popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                                    popupWindow.setFocusable(true);
                                    if (!popupWindow.isShowing()) {
                                        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
                                    }
                                    TextView tv_know = customView.findViewById(R.id.tv_know);
                                    tv_know.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (timer != null) {
                                                timer.cancel();
                                                timer = null;
                                            }
                                            pupDismiss();
                                        }
                                    });
                                }

                            } else {
                                DoneGoToMain();
                            }
                        }

                    } else {
                        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_WIFI_PARAM, HiChipDefines.HI_P2P_S_WIFI_PARAM.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, 0, wifiSelectMode, wifiSelectEncType, mWiFiName.getBytes(), mWiFiPassWord.getBytes()));
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                String ssid = et_wifi_name.getText().toString();
                                if (!TextUtils.isEmpty(ssid)) {
                                    WifiAdmin wifiAdmin = new WifiAdmin(getApplicationContext());
                                    handConnect(wifiAdmin, ssid);
                                }
                            }
                        }, 5000);
                    }
                } else {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_WIFI_CHECK, HiChipDefines.HI_P2P_S_WIFI_CHECK.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, 0, wifiSelectMode, wifiSelectEncType, mWiFiName.getBytes(), mWiFiPassWord.getBytes(), 1));
                }
                break;
            case HiCamera.CAMERA_CONNECTION_STATE_DISCONNECTED:
                break;
            case HiCamera.CAMERA_CONNECTION_STATE_WRONG_PASSWORD:
                HiToast.showToast(ConfigWiFiToDeviceTwoActivity.this, getString(R.string.device_info_error));
                dissmissLoadDialog();
                break;
        }
    }


    @Override
    public void receiveSessionState(HiCamera hiCamera, int i) {
        if (hiCamera != mMyCamera) {
            return;
        }
        Message msg = Message.obtain();
        msg.what = HiDataValue.HANDLE_MESSAGE_SESSION_STATE;
        msg.arg1 = i;
        mHandler.sendMessage(msg);
    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mMyCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    private void pupDismiss() {
        if (popupWindow != null) {
            popupWindow.dismiss();
            popupWindow = null;
            if (HiTools.isWifiConnected(ConfigWiFiToDeviceTwoActivity.this)) {
                WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                String SSID = wifiManager.getConnectionInfo().getSSID();
                SSID = SSID.substring(1, SSID.length() - 1);
                if (!TextUtils.isEmpty(SSID) && !SSID.equals(mDeviceWiFi)) {
                    Intent intent = new Intent(ConfigWiFiToDeviceTwoActivity.this, APConnectActivity.class);
                    intent.putExtra("ssid", mDeviceWiFi);
                    intent.putExtra("mCurrentPhoneWiFi", mDeviceWiFi);
                    startActivity(intent);
                }
            } else {
                Intent intent = new Intent(ConfigWiFiToDeviceTwoActivity.this, APConnectActivity.class);
                intent.putExtra("ssid", mDeviceWiFi);
                intent.putExtra("mCurrentPhoneWiFi", mDeviceWiFi);
                startActivity(intent);
            }
        }

    }


    //切换指定WIFI的功能
    private void handConnect(WifiAdmin wifiAdmin, String ssid) {
        WifiInfo info = wifiAdmin.mWifiInfo;
        WifiConfiguration tempConfig = wifiAdmin.IsExsits(ssid);
        if (tempConfig != null) {
            boolean isRemoveSucc = wifiAdmin.mWifiManager.removeNetwork(tempConfig.networkId);
            if (!isRemoveSucc) {
                Wificonnect(wifiAdmin, ssid);
            }
        }
        wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(ssid, et_wifi_password.getText().toString(), 3));
    }

    private void Wificonnect(WifiAdmin wifiAdmin, String ssid) {
        // 连接到外网
        WifiConfiguration mWifiConfiguration;
        WifiManager mWifiManager = wifiAdmin.mWifiManager;
        String SSID = ssid;
        String password = et_wifi_password.getText().toString();
        //检测指定SSID的WifiConfiguration 是否存在
        WifiConfiguration tempConfig = wifiAdmin.IsExsits(SSID);
        if (tempConfig == null) {
            //创建一个新的WifiConfiguration ，CreateWifiInfo()需要自己实现
            mWifiConfiguration = wifiAdmin.CreateWifiInfo(SSID, password, 3);
            int wcgID = mWifiManager.addNetwork(mWifiConfiguration);
            boolean b = mWifiManager.enableNetwork(wcgID, true);
        } else {
            //发现指定WiFi，并且这个WiFi以前连接成功过
            mWifiConfiguration = tempConfig;
            boolean b = mWifiManager.enableNetwork(mWifiConfiguration.networkId, true);
        }

    }


}
